package com.core;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;

import com.core.initialize.ClientChannelInitializer;

/**
 * 网络连接器
 * 
 * @author King
 * 
 */
public class NetConnector
{
	private static final Logger log = Logger.getLogger(NetConnector.class);
	private EventLoopGroup group;
	private Bootstrap b;
	private Channel channel;
	
	
	public NetConnector(ClientNetService engin,InetSocketAddress address) 
	{
		// netty connector初始化
		ClientChannelInitializer handler = new ClientChannelInitializer();
		handler.setEnginService(engin);
		this.group = new NioEventLoopGroup();
		this.b = new Bootstrap();
		this.b.group(group).channel(NioSocketChannel.class).handler(handler);
		
		
		log.warn("connect to " + address);
		try {
			ChannelFuture future = b.connect(address);
			this.channel = future.channel();
		} catch (Exception e) {
			this.group.shutdownGracefully();
		}
	}

	/**
	 * 关闭
	 */
	public void shutdown() {
		if(this.channel!=null)
			this.channel.close();
		if(this.group!=null)
			this.group.shutdownGracefully();
	}

	public Channel getChannel() {
		return channel;
	}
}
